/* eslint-disable no-console */
import { AsyncThunk, createAsyncThunk } from '@reduxjs/toolkit';

type AsyncFn<TArg, TReturn> = (arg: TArg) => Promise<TReturn>;

export const handleAsyncThunk = <TArg = undefined, TReturn = any>(
  name: string,
  asyncFn?: AsyncFn<TArg, TReturn>,
): AsyncThunk<TReturn, TArg, any> =>
  createAsyncThunk(name, async (arg: TArg, thunkApi) => {
    try {
      if (asyncFn) {
        const res = await asyncFn(arg);
        return res;
      }
      return arg as any;
    } catch (err: any) {
      return thunkApi.rejectWithValue(err.message);
    }
  });
